/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbeans;

import beans.Atualizacao;
import beans.Usuario;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.primefaces.event.FileUploadEvent;
import persistence.DAO;
import persistence.DAOUsuario;
import persistence.EMF;


/**
 *
 * @author alexandre
 */
@ManagedBean
@RequestScoped
public class ImagemMB {

    public ImagemMB() {
    }

    public void saveImage(FileUploadEvent event) throws FileNotFoundException, IOException {

        byte[] conteudo = event.getFile().getContents();
        ExternalContext externalContext =
                FacesContext.getCurrentInstance().getExternalContext();
        HttpServletResponse response =
                (HttpServletResponse) externalContext.getResponse();

        FacesContext aFacesContext = FacesContext.getCurrentInstance();
        ServletContext context =
                (ServletContext) aFacesContext.getExternalContext().getContext();
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        Usuario u = (Usuario) session.getAttribute("usuarioLogado");
        String caminho = context.getRealPath("/imagens/usuario");
        caminho += "/" + u.getId();
        File f = new File(caminho);
        f.mkdir();
        caminho += "/" + event.getFile().getFileName();
        FileOutputStream fos = new FileOutputStream(caminho);
        fos.write(conteudo);
        fos.close();
        File f2 = new File(context.getRealPath(u.getFotoPerfil()));
        f2.delete();
        u.setFotoPerfil("/imagens/usuario/" + u.getId() + "/" + event.getFile().getFileName());
        DAO dao = new DAO(EMF.getEntityManager(), Usuario.class);
        dao.atualiza(u);
        session.removeAttribute("usuarioLogado");
        session.setAttribute("usuarioLogado", u);
        UsuarioMB umb = new UsuarioMB();
        umb.setUs(u);
        Atualizacao a =new Atualizacao();
        a.setDataAtualiza(Calendar.getInstance().getTime());
        a.setUserPublica(u);
        a.setAlvo("Alterou a foto do perfil");
        a.setIdAlvo(Long.valueOf("2"));
        DAO daoat = new DAO(EMF.getEntityManager(), Usuario.class);
        daoat.salva(a);
        DAOUsuario daou = new DAOUsuario(EMF.getEntityManager());
        daou.atualizacoes(u, a);
    }
}
